<template>
  <div class="app-container">

    <div class="search-div">
      <!--<el-form label-width="70px" size="small">-->
      <!--  <el-row>-->
      <!--    <el-col :span="8">-->
      <!--      <el-form-item label="关 键 字">-->
      <!--        <el-input v-model="searchObj.keyword" style="width: 95%" placeholder="用户名/姓名/手机号码" />-->
      <!--      </el-form-item>-->
      <!--    </el-col>-->
      <!--    <el-col :span="8">-->
      <!--      <el-form-item label="操作时间">-->
      <!--        <el-date-picker-->
      <!--          v-model="createTimes"-->
      <!--          type="datetimerange"-->
      <!--          range-separator="至"-->
      <!--          start-placeholder="开始时间"-->
      <!--          end-placeholder="结束时间"-->
      <!--          value-format="yyyy-MM-dd HH:mm:ss"-->
      <!--          style="margin-right: 10px;width: 100%;"-->
      <!--        />-->
      <!--      </el-form-item>-->
      <!--    </el-col>-->
      <!--  </el-row>-->
      <!--    <el-row style="display:flex">-->
      <!--      <el-button type="primary" icon="el-icon-search" size="mini" @click="fetchData()">搜索</el-button>-->
      <!--      <el-button icon="el-icon-refresh" size="mini" @click="resetData">重置</el-button>-->
      <!--    </el-row>-->
      <!--  </el-form>-->
      <!--</div>-->

      <!-- 工具条 -->
      <div class="tools-div">
        <el-button type="success" icon="el-icon-plus" size="mini" @click="add">添 加</el-button>
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="exportUserExcel()"
        >导出</el-button>
      </div>

      <!-- 列表 -->
      <el-table
        v-loading="listLoading"
        :data="list"
        stripe
        border
        style="width: 100%;margin-top: 10px;"
      >
        <el-table-column
          type="index"
          label="序号"
          align="center"
          width="70"
        />
        <el-table-column prop="userAccount" label="账号" align="center" width="150" />
        <el-table-column prop="userName" label="昵称" align="center" width="150" />
        <!--<el-table-column label="头像" align="center" width="100">-->
        <!--  <template slot-scope="scope">-->
        <!--    <el-avatar :size="50" fit="fill" :src="scope.row.userAvatar" />-->
        <!--  </template>-->
        <!--</el-table-column>-->
        <el-table-column label="性别" align="center" width="80">
          <template slot-scope="scope">
            <span v-if="scope.row.gender === 0">男</span>
            <span v-else>女</span>
          </template>
        </el-table-column>
        <el-table-column prop="phone" align="center" label="电话" />
        <el-table-column label="是否禁用" align="center" width="80">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.status === 1"
              @change="switchStatus(scope.row)"
            />
          </template>
        </el-table-column>
        <el-table-column prop="createTime" align="center" label="创建时间" />

        <el-table-column label="操作" align="center" fixed="right">
          <template slot-scope="scope">
            <el-button
              type="warning"
              icon="el-icon-baseball"
              size="mini"
              title="分配角色"
              @click="showAssignRole(scope.row)"
            />
            <el-button type="primary" icon="el-icon-edit" size="mini" title="修改" @click="edit(scope.row.id)" />
            <el-button type="danger" icon="el-icon-delete" size="mini" title="删除" @click="deleteUser(scope.row.id)" />
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页组件 -->
      <el-pagination
        :current-page.sync="current"
        :total="total"
        :page-size="pageSize"
        style="padding: 30px 0; text-align: center;"
        layout="total, prev, pager, next, jumper"
        @current-change="fetchData"
      />

      <!-- 弹出框 -->
      <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="40%">
        <el-form ref="dataForm" :model="sysUser" label-width="100px" size="small" style="padding-right: 40px;">
          <el-form-item label="账号" prop="userAccount">
            <el-input v-model="sysUser.userAccount" />
          </el-form-item>
          <el-form-item v-if="!sysUser.id" label="密码" prop="password">
            <el-input v-model="sysUser.userPassword" type="password" />
          </el-form-item>
          <el-form-item label="昵称" prop="userName">
            <el-input v-model="sysUser.userName" />
          </el-form-item>
          <el-form-item label="手机" prop="phone">
            <el-input v-model="sysUser.phone" />
          </el-form-item>

          <el-form-item label="性别" prop="gender">
            <el-radio-group v-model="sysUser.gender" size="medium" @change="$forceUpdate()">
              <el-radio border :label="0">男</el-radio>
              <el-radio border :label="1">女</el-radio>
            </el-radio-group>
          </el-form-item>
          <!--<el-form-item label="性别" prop="gender">-->
          <!--  <el-upload-->
          <!--    :action="url"-->
          <!--    :show-file-list="false"-->
          <!--    list-type="picture-card"-->
          <!--    :headers="token"-->
          <!--    :on-success="handleAvatarSuccess"-->
          <!--  >-->
          <!--    <el-image-->
          <!--      v-if="sysUser.userAvatar !== ''"-->
          <!--      min-width="155"-->
          <!--      height="150"-->

          <!--      fit="fill"-->
          <!--    />-->
          <!--    <i v-else class="el-icon-plus" />-->
          <!--  </el-upload>-->
          <!--</el-form-item>-->
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button size="small" icon="el-icon-refresh-right" @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" icon="el-icon-check" size="small" @click="saveOrUpdate()">确 定</el-button>
        </span>
      </el-dialog>

      <el-dialog title="分配角色" :visible.sync="dialogRoleVisible">
        <el-form label-width="80px">
          <el-form-item label="账号">
            <el-input disabled :value="sysUser.userAccount" />
          </el-form-item>

          <el-form-item label="角色列表">
            <el-checkbox v-model="checkAll" :indeterminate="isIndeterminate" @change="handleCheckAllChange">全选
            </el-checkbox>
            <div style="margin: 15px 0;" />
            <el-checkbox-group v-model="userRoleIds" @change="handleCheckedChange">
              <el-checkbox v-for="role in allRoles" :key="role.id" :label="role.id">{{ role.roleName }}</el-checkbox>
            </el-checkbox-group>
          </el-form-item>
        </el-form>
        <div slot="footer">
          <el-button size="small" @click="dialogRoleVisible = false">取消</el-button>
          <el-button type="primary" size="small" @click="assignRole">保存</el-button>
        </div>
      </el-dialog>
    </div>
  </div></template>

<script>
import api from '@/api/system/user/user'
import roleApi from '@/api/system/role/role'
import fileApi from '@/api/file'
import download from '@/utils/download'
import store from '@/store'
import { getToken } from '@/utils/auth'

const defaultForm = {
  id: '',
  userAccount: '',
  userName: '',
  userPassword: '',
  phone: '',
  gender: 0,
  userAvatar: ''
}

export default {
  name: 'Index',
  // 定义数据模型
  data() {
    return {
      listLoading: true, // 数据是否正在加载
      list: [], // 用户列表
      total: 0, // 总记录数
      current: 1, // 页码
      pageSize: 5, // 每页记录数
      searchObj: {}, // 查询条件

      createTimes: [],

      dialogVisible: false,
      dialogTitle: '',
      sysUser: defaultForm,
      saveBtnDisabled: false,

      multipleSelection: [], // 批量删除选中的记录列表

      dialogRoleVisible: false,
      allRoles: [], // 所有角色列表
      userRoleIds: [], // 用户的角色ID的列表
      isIndeterminate: false, // 是否是不确定的
      checkAll: false, // 是否全选
      imageURL: '',
      url: '',
      token: {}

    }
  },
  // 页面渲染之前获取数据
  beforeMount() {
    if (store.getters.token) {
      this.token.token = getToken()
    }
    this.url = process.env.VUE_APP_BASE_API + '/admin/file/user/upload'
    this.fetchData()
  },
  methods: {

    handleAvatarSuccess(res) {
      console.log(res.data)
      this.sysUser.userAvatar = res.data
      // TODO 头像
      this.imageURL = '' + res.data
    },

    /**
     * 导出用户
     */
    async exportUserExcel() {
      const res = await fileApi.exportUserExcel(this.searchObj)
      console.log(res)
      download.excel(res, '用户信息')
    },

    // 展示分配角色
    showAssignRole(row) {
      this.sysUser = row
      this.dialogRoleVisible = true
      roleApi.getRolesByUserId(row.id).then(response => {
        console.log(response)
        this.allRoles = response.data.allRoles
        console.log(this.allRoles)
        this.userRoleIds = response.data.userRoleIds
        console.log(this.userRoleIds)
        this.checkAll = this.userRoleIds.length === this.allRoles.length
        this.isIndeterminate = this.userRoleIds.length > 0 && this.userRoleIds.length < this.allRoles.length
      })
    },

    /*
    全选勾选状态发生改变的监听
    */
    handleCheckAllChange(value) { // value 当前勾选状态true/false
      // 如果当前全选, userRoleIds就是所有角色id的数组, 否则是空数组
      this.userRoleIds = value ? this.allRoles.map(item => item.id) : []
      // 如果当前不是全选也不全不选时, 指定为false
      this.isIndeterminate = false
    },

    /*
    角色列表选中项发生改变的监听
    */
    handleCheckedChange(value) {
      const { userRoleIds, allRoles } = this
      this.checkAll = userRoleIds.length === allRoles.length && allRoles.length > 0
      this.isIndeterminate = userRoleIds.length > 0 && userRoleIds.length < allRoles.length
    },

    // 分配角色
    assignRole() {
      const assignRoleRequest = {
        userId: this.sysUser.id,
        roleIdList: this.userRoleIds
      }
      roleApi.assignRoles(assignRoleRequest).then(response => {
        this.$message.success(response.message || '分配角色成功')
        this.dialogRoleVisible = false
        this.fetchData(this.page)
      })
    },

    /**
     * 切换用户状态
     *
     * @param row
     */
    switchStatus(row) {
      row.status = row.status === 1 ? 0 : 1
      // TODO 后端返回报异常，按钮依旧会改变
      api.updateStatus({ id: row.id, status: row.status }).then(response => {
        if (response.code === 0) {
          this.$message.success(response.message || '操作成功')
          this.fetchData(this.current)
        }
      })
    },

    /**
     * 弹出添加的表单
     */
    add() {
      this.dialogTitle = '新建用户'
      this.dialogVisible = true
      this.sysUser = {}
      this.sysUser.gender = 0
    },

    /**
     * 弹出编辑的表单
     *
     * @param id
     */
    async edit(id) {
      this.dialogTitle = '编辑用户'
      this.dialogVisible = true
      // api.getUserById(id).then(response => {
      //  this.sysUser = response.data
      // })
      const res = await api.getUserById(id)
      this.sysUser = res.data
    },

    /**
     * 发送添加或更新请求
     */
    saveOrUpdate() {
      if (!this.sysUser.id) {
        this.addUser()
      } else {
        this.updateUser()
      }
    },

    /**
     * 创建用户
     *
     * @param sysUserAddRequest
     */
    async addUser() {
      // api.addUser(this.sysUser).then(response => {
      //  this.$message.success(response.message || '添加成功')
      //  this.dialogVisible = false
      //  this.fetchData(this.current)
      // })
      const response = await api.addUser(this.sysUser)
      this.$message.success(response.message || '添加成功')
      this.dialogVisible = false
      this.fetchData(this.current)
    },

    /**
     * 删除用户
     *
     * @param id
     */
    deleteUser(id) {
      this.$confirm('此操作将永久删除该记录, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        // TODO 删除最后一个有bug
        const response = await api.deleteUser({ id })
        this.fetchData(this.current)
        this.$message.success(response.message || '删除成功')
      }).catch(() => {})
    },

    // 当多选选项发生变化的时候调用
    handleSelectionChange(selection) {
      console.log(selection)
      this.multipleSelection = selection
    },

    /**
     * 批量删除
     */
    batchDeleteUser() {
      if (this.multipleSelection.length === 0) {
        this.$message.warning('请选择要删除的记录！')
        return
      }
      this.$confirm('此操作将永久删除该记录, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 点击确定，远程调用ajax
        // 遍历selection，将id取出放入id列表
        const idList = []
        this.multipleSelection.forEach(item => {
          idList.push(item.id)
        })
        // 调用api
        return api.batchDeleteUser(idList)
      }).then((response) => {
        // TODO 是否要跳到当前页
        this.fetchData()
        this.$message.success(response.message)
      }).catch(error => {
        if (error === 'cancel') {
          this.$message.info('取消删除')
        }
      })
    },

    /**
     * 更新用户
     *
     * @param sysUserUpdateRequest
     */
    updateUser(sysUserUpdateRequest) {
      api.updateUser(this.sysUser).then(response => {
        this.$message.success(response.message || '修改成功')
        this.dialogVisible = false
        this.fetchData(this.current)
      })
    },

    /**
     * 重置查询表单
     */
    resetData() {
      this.searchObj = {}
      this.fetchData()
    },

    /**
     * 分页获取用户列表
     *
     * @param pageNum
     */
    async fetchData(pageNum = 1) {
      try {
        this.current = pageNum
        const response = await api.listUserByPage(this.current, this.pageSize, this.searchObj)
        this.list = response.data.records
        this.total = response.data.total
        this.current = response.data.current
        this.pageSize = response.data.size
      } catch (error) {
        this.$message.error('分页获取用户列表异常 ', error.getMessage())
      } finally {
        this.listLoading = false
      }
    }
  }
}
</script>

<style scoped>
.avatar-uploader .el-upload {
  border: 1px dashed #b5b3b3;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
